/**
 * @Description:
 * @author GS
 * @date 2013-8-22 下午2:02:30
 */
package com.platform.cdcs.tool;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.platform.cdcs.R;
import com.trueway.app.uilib.widget.TwDialogBuilder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

/**
 * @author GS 版本更新对话框
 */
public class UpdateManager {

    private static final int DOWNLOAD = 1;// 下载中
    private static final int DOWNLOAD_FINISH = 2;// 下载结束
    private static final int DOWNLOAD_ERROR = 3;// 下载失败
    private final static String SOFT_UPDATE_TITLE = "软件更新";
    private final static String SOFT_UPDATE_INFO = "检测到新版本，立即更新吗？";
    private final static String SOFT_UPDATE_UPDATE = "更新";
    HashMap<String, String> mHashMap;// 保存解析的XML信息
    private Context mContext;
    private String mSavePath;// 下载保存路径
    private String saveName = "app.apk";// 下载保存文件名
    private String msg = "";
    private int isMandatory = 0;

    private int progress;// 记录进度条数量
    private boolean cancelUpdate = false;// 是否取消更新

    private String appurl;// app获取地址
    private long size;
    /**
     * 下载APK对话框
     */
    private ProgressDialog m_pDialog;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD:// 正在下载
                    m_pDialog.setProgress(progress);// 设置进度条位置
                    break;
                case DOWNLOAD_FINISH:
                    installApk();// 安装文件
                    break;
                case DOWNLOAD_ERROR:
                    new AlertDialog.Builder(mContext).setTitle("提示").setMessage("无SD卡，无法下载更新!").show();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(Context context, HashMap<String, String> mHashMap) {
        this.mContext = context;
        this.mHashMap = mHashMap;
    }

    public UpdateManager(Context context, String appurl) {
        this.mContext = context;
        this.appurl = appurl;
    }

    /**
     * 检测软件更新
     */
    public void checkUpdate(boolean infoFlag) {
        if (isUpdate()) {
            // 显示提示对话框
            showNoticeDialog();
        } else {
            if (infoFlag) {
                Toast.makeText(mContext, R.string.update_no, Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    private boolean isUpdate() {
        // 获取当前软件版本

        if (null != mHashMap) {
            float versionCode = getVersionCode(mContext);
            try {
                float serviceCode = Float.parseFloat(mHashMap.get("number"));
                // 版本判断

                if (serviceCode > versionCode) {
                    this.appurl = mHashMap.get("url");
                    this.saveName = mHashMap.get("name");
                    this.msg = mHashMap.get("msg");
                    if (mHashMap.containsKey("size")) {
                        try {
                            this.size = Long.parseLong(mHashMap.get("size"));
                        } catch (Exception e) {

                        }
                    }
                    if (TextUtils.isEmpty(msg)) {
                        msg = "";
                    }
                    if (mHashMap.containsKey("update") && !TextUtils.isEmpty(mHashMap.get("update"))) {
                        try {
                            this.isMandatory = Integer.parseInt(mHashMap.get("update"));
                        } catch (Exception e) {
                            this.isMandatory = 0;
                        }
                    }
                    return true;
                }
            } catch (Exception e) {
                return false;
            }

        }
        return false;
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private float getVersionCode(Context context) {
        float versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = Float.parseFloat(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 显示是否更新对话框
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void showNoticeDialog() {
        try {
            if (isMandatory != 0) {
                new TwDialogBuilder(mContext).setTitle(SOFT_UPDATE_TITLE).setMessage(SOFT_UPDATE_INFO + "\n" + msg)
                        .setCancelable(false).setPositiveButton(R.string.update, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        downApkDialog();// 显示下载对话框
                        new downloadApkThread().start();// 启动新线程下载软件
                    }

                }).create().show();
            } else {
                new TwDialogBuilder(mContext).setTitle(SOFT_UPDATE_TITLE).setMessage(SOFT_UPDATE_INFO + "\n" + msg)
                        .setPositiveButton(R.string.update, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                downApkDialog();// 显示下载对话框
                                new downloadApkThread().start();// 启动新线程下载软件
                            }

                        }).setNegativeButton(R.string.next, null).create().show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    ;

    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, saveName);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri =
                    FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", apkfile);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile),
                    "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
        try {
            Window window = ((Activity) mContext).getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } catch (Exception e) {

        }
    }

    private void downApkDialog() {
        m_pDialog = new ProgressDialog(mContext); // 创建ProgressDialog对象
        m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 设置进度条风格，风格为长形
        m_pDialog.setTitle("提示"); // 设置ProgressDialog 标题
        m_pDialog.setMessage("正在更新中..."); // 设置ProgressDialog 提示信息
        m_pDialog.setProgress(100); // 设置ProgressDialog 进度条进度
        m_pDialog.setIndeterminate(false); // 设置ProgressDialog 的进度条是否不明确
        m_pDialog.setCanceledOnTouchOutside(false);
//		m_pDialog.setCancelable(false); // 设置ProgressDialog 是否可以按退回按键取消
        // m_pDialog.setButton(AlertDialog.BUTTON_POSITIVE, "取消",
        // new DialogInterface.OnClickListener() {
        // public void onClick(DialogInterface dialog, int i) {
        // dialog.dismiss();
        // }
        // });
        m_pDialog.show(); // 让ProgressDialog显示
        m_pDialog.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface arg0) {
                cancelUpdate = true;
            }
        });
    }

    /**
     * 下载文件线程
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(appurl);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    long length = conn.getContentLength();
                    if (length == 0) {
                        length = size;
                    }
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, saveName);
                    if (apkFile.exists()) {
                        apkFile.delete();
                    }
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024 * 4];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    }
                    while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                } else {
                    // 下载完成
                    mHandler.sendEmptyMessage(DOWNLOAD_ERROR);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            if (m_pDialog != null && m_pDialog.isShowing()) {
                m_pDialog.dismiss();
            }
        }
    }
}
